package com.wan.servlet.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wan.dao.role.RoleDaoImpl;
import com.wan.pojo.Role;
import com.wan.pojo.User;
import com.wan.service.role.RoleServiceImpl;
import com.wan.service.user.UserServiceImpl;
import com.wan.util.Constants;
import com.wan.util.PageSupport;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//实现servlet复用，走的一个请求下的不同方法
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method.equals("savepwd") && method != null) { // 保存密码
            this.updatePwd(req,resp);
        }else if (method.equals("pwdmodify") && method != null){ // 修改密码
            this.checkOldPwd(req,resp);
        }else if (method.equals("query") && method != null) { // 查询功能
            this.query(req,resp);
        }else if (method.equals("add")) {  // 添加用户
            this.add(req,resp);
        }else if (method.equals("getrolelist")) { // 拿到角色列表
            this.getRoleList(req,resp);
        }else if (method.equals("ucexist")) { // 判断用户是否已经存在
            this.ucExist(req, resp);
        }else if (method.equals("deluser")) { // 删除一个用户
            this.deleteUser(req, resp);
        }else if (method.equals("modify")) { // 页面跳转，需要携带用户参数
            this.modifyUser(req, resp);
        }else if (method.equals("modifyexe")) { // 修改用户信息
            this.modifyUserById(req, resp);
        }else if (method.equals("view")) { // 查看用户信息，需要携带用户实体
            this.sendView(req, resp);
        }
    }
    // 转发到查看视图
    public void sendView (HttpServletRequest req, HttpServletResponse resp) {
        String uid = req.getParameter("uid");
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserById(Integer.valueOf(uid));
        if (uid != null) {
            try {
                req.setAttribute("user",user);
                req.getRequestDispatcher("/jsp/userview.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 将请求转发到修改用户信息界面
    public void modifyUser (HttpServletRequest req, HttpServletResponse resp) {
        // 获取前端传递过来的id
        String uid = req.getParameter("uid");
        System.out.println("modifyUser--->"+uid);
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.getUserById(Integer.valueOf(uid));
        if (user != null) {
            try {
                req.setAttribute("user",user);
                req.getRequestDispatcher("/jsp/usermodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //收集用户填写的信息
    public void modifyUserById (HttpServletRequest req, HttpServletResponse resp) {
        // 获取前端传递过来的id
        String id =req.getParameter("uid");
        System.out.println("modifyUserById--->"+id);
        // 获取用户填入的数据
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");
        // 将这些信息封装到一个User中
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyDate(new Date(System.currentTimeMillis()));

        User loader = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int modifyBy = loader.getId();

        // 调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        int impactCount = userService.updateUser(user,modifyBy);
        if (impactCount > 0) {
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            try {
                req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    // 删除一个用户
    public void deleteUser (HttpServletRequest req, HttpServletResponse resp) {
        // 通过用户的userCode进行删除
        String userId = req.getParameter("uid");
        // 拿到要删除用户的用户编码
        UserServiceImpl userService = new UserServiceImpl();
        // 查询到受影响的行数
        int impactCount = userService.deleteUserById(Integer.valueOf(userId));
        // 用map把返回信息存储起来，方便后续转换成json的格式
        Map<String, String> resultMap = new HashMap<String,String>();

        if (userId == null){
            resultMap.put("delResult","notexist");
        } else {
            // 如果受影响的行数大于0，那么表示删除成功
            if (impactCount > 0) {
                resultMap.put("delResult","true");
            }else if (impactCount == 0) {
                resultMap.put("delResult","false");
            }
        }
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 查询用户是否已经存在
    public void ucExist (HttpServletRequest req, HttpServletResponse resp) {
        // 获得用户名
        String userCode = req.getParameter("userCode");
        // 根据返回的数量查询是否存在
        int impactCount = 0;
        // 存储查询的映射情况
        Map<String, String> resultMap = new HashMap<String,String>();

        UserServiceImpl userService = new UserServiceImpl();

        if (userCode != null) {
            impactCount = userService.userExist(userCode);
        }
        System.out.println(impactCount);
        if (impactCount > 0) {
            resultMap.put("userCode","exist");
        } else {
            resultMap.put("userCode","notExist");
        }
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获得用户角色列表，供ajax调用
    public void getRoleList (HttpServletRequest req, HttpServletResponse resp) {
        // 用map把返回信息存储起来，方便后续转换成json的格式
        Map<String, String> resultMap = new HashMap<String,String>();

        // 获得角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();

        // 将map转换为json
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(roleList));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 添加一个用户的方法
    public void add (HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        // 前端获取数据,传递过来不会有空的
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        // 将相关信息封装到对象中去
        user.setId(user.getId());
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreatedBy(user.getId());
        user.setCreationDate(new Date(System.currentTimeMillis()));


        // 准备执行语句
        UserServiceImpl userService = new UserServiceImpl();
        int impactCount = userService.addUser(user);
        if (impactCount > 0) {
            try {
                // 请求转发
                req.getRequestDispatcher("/jsp/user.do?method=query").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 重点，难点
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        // 从前端获取数据
        String queryUsername = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");

        // 显示的赋有效值，为了不报错误，如果不做这个工作，可能读到的是个空
        int queryUserRole = 0 ;

        // 获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        // 第一次走这个请求，一定是第一页，页面大小是固定的
        // 这个大小可以写到配置文件中，那样更容易更改，在这写的固定了就不好改
        int pageSize = 5;
        int currentPageNum = 1;

        // 给出一些默认情况
        if (queryUsername == null) {
            queryUsername="";
        }
        if (temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp); // 给查询赋值0,1,,2,3,
        }
        if (pageIndex != null) {
            currentPageNum = Integer.parseInt(pageIndex);//解析出来的值就是1，这是默认情况下的东西
        }

        // 获取用户的总数(分页，上一页，下一页，首页，尾页)
        int totalCount = userService.getUserCount(queryUsername, queryUserRole);

        PageSupport pageSupport = new PageSupport(); // 总页数支持
        pageSupport.setCurrentPageNo(currentPageNum);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        // 根据查询到的数量、页面大小、当前页，计算出页面总数
        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 如果页面要小于1，就显示第一页
        if (totalPageCount < 1) {
            currentPageNum = 1;
        }else if (currentPageNum > totalPageCount) {
            currentPageNum = totalPageCount;
        }

        System.out.println("queryUsername----->"+queryUsername);
        // 获取用户列表展示 中间的一大堆都是为了执行这个代码，获得用户列表
        // 为了sql的正常运行，不能让任何一个数据的问题使得sql不能运行
        userList = userService.getUserList(queryUsername, queryUserRole, currentPageNum, pageSize);
        req.setAttribute("userList",userList);

        // 获得角色列表
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);

        // 返回页数，分页的相关支持
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNum);
        req.setAttribute("queryUserName",queryUsername);
        req.setAttribute("queryUserRole",queryUserRole);

        // 携带参数，返回前端看看
        try {
            req.getRequestDispatcher("/jsp/userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){

        // 拿到Session存储的对象 ,这个对象里面有这个人的所有的相关信息
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        // 拿到需要修改的新密码
        String newpassword = req.getParameter("newpassword");

        UserServiceImpl userService = new UserServiceImpl();
        boolean flag = false;
        // 如果从前端获取的用户和密码都不为空的时候调用Service层的相关方法
        if (user != null && newpassword != null) {
            flag = userService.updatePwd(user.getId(), newpassword);
            if(flag) {
                req.setAttribute("message","密码修改成功，请返回登录页面重新登录");
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message","密码修改失败！");
            }
        }else{
            req.setAttribute("message","获取不到当前用户或者新密码有问题");
        }

        try {
            req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 检查旧密码是否正确
    public void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) {
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        // 用map把返回信息存储起来，方便后续转换成json的格式
        Map<String, String> resultMap = new HashMap<String,String>();

        // 如果Session 为空，代表用户不存在或者Session已经过期
        if(o == null) {
            resultMap.put("result","sessionerror");
        }else if(o != null && oldpassword == null) { // 用户登录了，但是没填旧密码
            resultMap.put("result","error");
        }else if( o !=null && oldpassword != null) { // 查到了，并且填了旧密码
            if (((User)o).getUserPassword().equals(oldpassword)){ // 填的旧密码正确
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false"); // 填的旧密码不正确
            }
        }
        try {
            // 要返回json格式
            resp.setContentType("application/json");
            // 得到流
            PrintWriter writer = resp.getWriter();
            // 以json的格式写出
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
